package io.hepu.robotize.schedule;

import io.hepu.robotize.IConstant;
import io.hepu.robotize.aop.RedisId;
import io.hepu.robotize.auth.JRedis;
import io.hepu.robotize.base.BaseService;
import io.hepu.robotize.util.ClassScaner;
import io.hepu.robotize.util.JAnnotation;
import io.hepu.robotize.util.Limits;
import io.hepu.robotize.util.Springs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Set;

@Slf4j
@Component
public class RedisIdRunner implements CommandLineRunner {
    @Override
    public void run(String... args) {
        log.info("Starting load entity max id to redis");
        Set<Class<?>> classes = ClassScaner.scan("io.hepu.robotize.model", RedisId.class);
        for (Class<?> clz : classes) {
            RedisId redisId = JAnnotation.ifPresent(clz, RedisId.class);
            if (Limits.nonNull(redisId)) {
                Class<?> provider = redisId.provider();
                BaseService<?, ?, ?> service = (BaseService<?, ?, ?>) Springs.getBean(provider);
                Serializable lastKey = service.findLastId(redisId.table());
                Serializable primaryKey = Limits.isNull(lastKey) ? redisId.id() : lastKey;
                String cacheKey = redisId.prefix() + redisId.table();
                JRedis.set(cacheKey, primaryKey.toString());
            }
        }
    }
}
